//
//  POIMapView.m
//  WikiXing
//
//  Created by Hu Shun on 12/1/09.
//  Copyright 2009 eTag Media. All rights reserved.
//

#import "POIMapView.h"
#import "PlaceMark.h"
#import "Constants.h"

#define BACKCOLOR [UIColor colorWithRed:144.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:1.0]

@implementation POIMapView
@synthesize thePOIArray,region;
@synthesize progressInd;
@synthesize currrentLocation;
@synthesize isGettingDirection;
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initNib:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
	CGRect theFrame = CGRectMake(0, 0, 320, 460);
	UIView *tempView = [[UIView alloc] initWithFrame:theFrame];
	self.view = tempView;
	[tempView release];
	
	locationManager = [[CLLocationManager alloc] init];
	[locationManager setDelegate:self];
	[locationManager setHeadingFilter:1];
		
	self.navigationItem.title = _(@"Maps");
	
	UIBarButtonItem  *doneBtn = [[UIBarButtonItem alloc] initWithTitle:_(@"Locate") style:UIBarButtonItemStylePlain target:self action:@selector(doLocateSelf)];
	self.navigationItem.rightBarButtonItem = doneBtn;
	[doneBtn release];
	
	mapView=[[MKMapView alloc] initWithFrame:self.view.bounds];
	mapView.showsUserLocation=NO;
	mapView.mapType=MKMapTypeStandard;
	mapView.delegate=self;
	if (region.center.latitude==0){
		MKCoordinateSpan span;
		span.latitudeDelta=0.06;
		span.longitudeDelta=0.06;
		
		CLLocationCoordinate2D location;
		
		location.latitude=[@"31.1856344" floatValue];
		location.longitude=[@"121.517347086639" floatValue];
		region.span=span;
		region.center=location;
	}
	
	[mapView setRegion:region animated:FALSE];
	[mapView regionThatFits:region];
	[self.view insertSubview:mapView atIndex:0];
	CGRect frame = CGRectMake(144, 204, 32, 32);
	progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];
	[progressInd startAnimating];
	progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
	[self.view addSubview:progressInd];
	isGettingDirection = NO;
	return self;
}

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)viewDidAppear:(BOOL)animated {
	
	Boolean Internet = TRUE;
		
	CLLocationCoordinate2D location;
	
	location.latitude=[@"31.1856344" floatValue];
	location.longitude=[@"121.517347086639" floatValue];
	currrentLocation= [[[PlaceMark alloc] initWithCoordinate:location] retain];
	currrentLocation.titletext = @"当前位置";
	if (Internet) {
		[mapView setRegion:region animated:YES];
		[mapView regionThatFits:region];
		[mapView addAnnotations:thePOIArray];
		[mapView addAnnotation:currrentLocation];
	} else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Can not connect to the network" message:@"Please have a network connection" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = NO;
	[super viewDidAppear:animated];
}
- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[progressInd startAnimating];
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = YES;
	
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyPin"];
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
	annView.pinColor = MKPinAnnotationColorRed;

	if([((PlaceMark *)annotation).titletext isEqualToString:@"当前位置"]){
		annView.pinColor = MKPinAnnotationColorGreen;
	}
    annView.calloutOffset = CGPointMake(-5, 5);
	if(![((PlaceMark *)annotation).titletext isEqualToString:@"当前位置"]){
		annView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
			annView.canShowCallout = YES;
	}
		
	annView.enabled = YES;
	
    return annView;
	

}
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	[mapView removeAnnotations:thePOIArray];
	[mapView removeAnnotation:currrentLocation];
}

-(void)done {
	[self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[locationManager release];
	[mapView release];
	[progressInd release];
    [super dealloc];
}

#pragma mark -
#pragma mark CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
	//[self setMapLocation:newLocation.coordinate distance:300 animated:NO];
	[mapView setCenterCoordinate:newLocation.coordinate animated:YES	];
	[locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
	[locationManager stopUpdatingLocation];
	[locationManager stopUpdatingHeading];
	[[locationManager viewForAnnotation:[mapView userLocation]] setTransform:CGAffineTransformIdentity];
	/*
	 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops" message:[NSString stringWithFormat:@"%@",NSLocalizedString(@"LocationManagerErrorMessage",nil)] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	 [alert show];
	 [alert release];
	 */
}


- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager{//遇到电磁干扰时，是否弹出按8字形摆动iPhone校准指南针的界面。
	return YES;
}

#pragma mark -
#pragma mark Actions
-(void)doLocateSelf
{
	CGPoint userLocationPoint = [mapView convertCoordinate:[mapView userLocation].coordinate toPointToView:mapView];
	if ([locationManager locationServicesEnabled]) {
		[locationManager startUpdatingLocation];
	}
	
	[mapView setCenterCoordinate:[mapView.userLocation coordinate] animated:YES];
}

@end
